#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>

#define NN 64

int main(int argc, char const* argv[])
{
    char buf[NN]={'\0'};
    char text[NN]={'\0'};
    int client_socket = socket(AF_INET,SOCK_STREAM,0);
    if (client_socket==-1)
    {
        perror("socket err\n");
        return -1;
    }

    struct sockaddr_in server_addr;
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(8888);
    server_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
    if(connect(client_socket,(struct sockaddr*)&server_addr,sizeof(server_addr))==-1)
    {
        perror("connect err\n");
        close(client_socket);
        return -1;
    }

    while (1)
    {
        printf("请输入要传输的文件:\n");
        scanf("%s",text);
        if (strcmp("quit",text)==0)//输入quit退出
        {
            break;
        }
        int fd=open(text,O_RDONLY);//打开文件
        if (fd==-1)
        {
            perror("open err\n");
            close(client_socket);
            return -1;
        }
        
        char size[4]={0};//文件大小
        *size=lseek(fd,0,SEEK_END);//获取文件长度
        char namelen[4]={0};
        *namelen=strlen(text);//获取文件名长度

        lseek(fd,0,SEEK_SET);
        send(client_socket,namelen,4,0);//发送文件名长度
        send(client_socket,text,*(int*)namelen,0);//发送文件名
        send(client_socket,size,4,0);//发送文件长度

        while ((read(fd,buf,NN))!=0)//循环发送文件
        {
            send(client_socket,buf,NN,0);
        }

        printf("文件传输完毕!\n");
        int ret =0;
        ret=recv(client_socket,buf,NN,0);
        printf("%s\n",buf);
        close(fd);
    }
    
    close(client_socket);

    return 0;
}